using System;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
	private Rigidbody body;
	
	private float horizontalSensibility = 0.05f;
	private float minimumX = 0;
	private float maximumX = 90;
	private float rotationX = 0;
	
	private float rotationY = 0;
	private float minimumY = -50.0f;
	private float maximumY = 5;
	private float sensitivityY = 0.05f;
	
	public  bool isLaunched = false;

	
	public void Start()
	{
		body = gameObject.AddComponent<Rigidbody>();
		body.mass = 10.0f;
		body.useGravity = true;
		body.freezeRotation = true;
	}
	
	public void OnCollisionEnter(Collision collision)
	{
		Debug.Log("Colidiu!");
	}
	
	public void Update()
	{
		if(!isLaunched)
			return;
		
		rotationX += Input.GetAxis("Mouse X") * horizontalSensibility;
		rotationX = ClampAngle(rotationX * horizontalSensibility, minimumX, maximumX);
		
		// xQuaternion = Quaternion.AngleAxis(rotationX, Vector3.up);
		// yQuaternion = Quaternion.AngleAxis(rotationY, Vector3.right);
		transform.localRotation = Quaternion.AngleAxis(rotationX, Vector3.right);
		
		//transform.RotateAroundLocal(Vector3.up, Input.GetAxis("Mouse X") * sensitivityY);
		float lateralSpeed = new Vector2(body.velocity.x, body.velocity.z).magnitude;
		body.velocity = new Vector3(transform.forward.x * lateralSpeed, body.velocity.y, transform.forward.z * lateralSpeed);
	}
	
	public void Launch(Transform direction)
	{
		body.velocity = direction.forward * rigidbody.velocity.magnitude;
		// body.AddForce(new Vector3(body.velocity.x + 50, body.velocity.y, body.velocity.z + 40), ForceMode.Impulse);
		
		// body.AddForceAtPosition(new Vector3(body.velocity.x + 50, body.velocity.y, body.velocity.z + 40), Vector3.left, ForceMode.Impulse);
		// body.velocity = 
		body.velocity = new Vector3(transform.forward.x + 100, transform.forward.y, transform.forward.z + 50);
		
		isLaunched = true;
	}
	
	public void Hide()
	{
		GetComponentInChildren<MeshRenderer>().enabled = false;
		// GetComponent<MeshRenderer>().enabled = false;
	}
	
	public void Show()
	{
		GetComponentInChildren<MeshRenderer>().enabled = true;
		// GetComponent<MeshRenderer>().enabled = true;
	}
	
	public static float ClampAngle(float angle, float min, float max)
	{
		if (angle < -360F)
			angle += 360F;
		if (angle > 360F)
			angle -= 360F;
		return Mathf.Clamp (angle, min, max);
	}
	
}

